//
//  NetworkManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/23.
//

import Foundation
import Moya

class QiniuManager {
    static let shared = QiniuManager()
    
    private let provider: MoyaProvider<QiniuApi>
    
    private init() {
        provider = MoyaProvider<QiniuApi>()
    }
    //统一请求处理
    private func request<M: Codable>(_ target: QiniuApi, modeType: M.Type) async throws-> M {
        try await withCheckedThrowingContinuation({ continuation in
            provider.request(target) { result in
                //调用统一接口处理, filterCode指定资源不存在或已被删除。   目标资源已存在。
                dealNetResult(result: result, modeType: modeType, filterCode: [612,614]) {
                    continuation.resume(returning: $0)
                } fail: {
                    continuation.resume(throwing: $0)
                }
            }
        })
    }
}

//接口请求
extension QiniuManager {
    
    
    func upload<M: Codable>(fileURL: URL, key: String, modeType: M.Type) async throws-> M {
        let fileData = try Data(contentsOf: fileURL)
        return try await upload(fileData: fileData, key: key, modeType: modeType)
    }
    
    func upload<M: Codable>(image: UIImage, key: String, modeType: M.Type) async throws-> M {
        let fileData = image.jpegData(compressionQuality: 0.8)
        return try await upload(fileData: fileData!, key: key, modeType: modeType)
        
    }
    
    func upload<M: Codable>(url: URL, key: String, modeType: M.Type) async throws-> M {
        // 使用内存映射方式读取文件（适合中小文件）
            let fileData = try Data(contentsOf: url, options: .mappedIfSafe)
            return try await upload(fileData: fileData, key: key, modeType: modeType)
        
    }
    
    
    //上传图片
    func upload<M: Codable>(fileData: Data, key: String, modeType: M.Type) async throws-> M {
        let result = QiniuUtils().getHttpBody(fileData: fileData,key: key)
        let body = result.0
        let boundary = result.1
        let api : QiniuApi = .upload(httpBody: body, boundary: boundary)
        return try await request(api, modeType: modeType)
    }
    //删除图片
    func delete<M: Codable>(url: String, modeType: M.Type) async throws-> M {
        let qiniu = QiniuUtils()
        let fileName = qiniu.getKey(url: url)
        return try await delete2(fileName: fileName, modeType: modeType)
    }
    
    //删除图片
    func delete2<M: Codable>(fileName: String, modeType: M.Type) async throws-> M {
        let qiniu = QiniuUtils()
        let encoded = qiniu.deletegetEencodedUrl(fileName: fileName)
        let token = qiniu.deleteToken(fileName: fileName)
        let api : QiniuApi = .delete(token: token, encoded: encoded)
        return try await request(api, modeType: modeType)
    }
    
    
    //下载文件
    func download(url: String) async throws-> Data {
        let api : QiniuApi = .download(url: url)
        return try await request(api, modeType: Data.self)
    }
}
